import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import utils from '@/utils/utils'
import store from '@/store'
import router from '../router/index'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000, // request timeout
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*', 
        'Cache-Control': 'no-cach'
    }
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent

        if (store.getters.token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['X-Token'] = getToken()
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data
        if (res.code == 0) {
            return Promise.resolve(res)
        }
        // if (res.code === -1) { //通用异常
        //     utils.msg.error(res.message || 'Error')
        // } else  if (res.code === 2) { //登录信息失效
        //     // to re-login
        //     MessageBox.confirm('登录信息失效', 'Confirm logout', {
        //         confirmButtonText: 'Re-Login',
        //         cancelButtonText: 'Cancel',
        //         type: 'warning'
        //     }).then(() => {
        //         store.dispatch('user/resetToken').then(() => {
        //             location.reload()
        //         })
        //     })
        else if (res.code == '-10') {
            Message.error(res.message)
            setTimeout(() => {
                router.push({
                    path: '/login'
                })
            }, 1000)
        }
        else {
            Message.error(res.message)
            // return Promise.reject(new Error(res.message || 'Error'))
            return Promise.reject(res.message)
        }

    },
    error => {
        console.log('err' + error) // for debug
        utils.msg.error(error.message || 'Error')
        return Promise.reject(error)
    }
)

export default service
